import 'package:flutter_admin/models/odoo/stock_quant.dart';
import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/stock_picking_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/pages/odoo/material/cpk_print/print.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';
import 'cpk_print_dialog.dart';

class CpkPrintList extends StatefulWidget {
  CpkPrintList({Key? key}) : super(key: key);
  @override
  _CpkPrintListState createState() => _CpkPrintListState();
}

class _CpkPrintListState extends State<CpkPrintList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  StockQuant stockQuant = StockQuant();
  List<StockQuant> selectedList = [];
  late List<SelectOptionVO> locationtypeList = [];

  DateFormat format = DateFormat('yyyy-MM-dd');

  //工厂名称
  List<SelectOptionVO> locationIdList = [];
  //车间名称
  List<SelectOptionVO> workshopIdList = [];

  @override
  void initState() {
    super.initState();
    stockQuant.createDate = Utils.getDate();
    stockQuant.writeDate = Utils.getDate();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    workshopIdList = await DynamicDataApi.getModelSelect(
        active: false,
        model: "hr.department",
        name: "complete_name",
        key: 'parent_id',
        operator: "!=",
        val: null);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '投产开始时间',
            value: stockQuant.createDate,
            lastDate: isNotBlank(stockQuant.writeDate)
                ? format.parse(stockQuant.writeDate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockQuant.createDate = v;
              setState(() {});
            },
            onSaved: (v) {
              stockQuant.createDate = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '投产结束时间',
            value: stockQuant.writeDate,
            firstDate: isNotBlank(stockQuant.createDate)
                ? format.parse(stockQuant.createDate!)
                : null,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockQuant.writeDate = v;
              setState(() {});
            },
            onSaved: (v) {
              stockQuant.writeDate = v;
            },
          ),
          CryInput(
            width: 160,
            label: '生产单号',
            value: stockQuant.productorderno,
            onSaved: (v) {
              stockQuant.productorderno = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品编码',
            value: stockQuant.productCode,
            onSaved: (v) {
              stockQuant.productCode = v;
            },
          ),
          CryInput(
            width: 160,
            label: '产品名称',
            value: stockQuant.productName,
            onSaved: (v) {
              stockQuant.productName = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('生产订单号')),
        DataColumn(label: Text('投产日期')),
        DataColumn(label: Text('产品编码')),
        DataColumn(label: Text('产品名称')),
        DataColumn(label: Text('规格型号')),
        DataColumn(label: Text('数量')),
        DataColumn(label: Text('计量单位')),
      ],
      getCells: (m) {
        StockQuant stockQuant = StockQuant.fromMapPrint(m);
        return [
          DataCell(Text(stockQuant.productorderno ?? '--')),
          DataCell(Text(Utils.timeUTC(stockQuant.datas))),
          DataCell(Text(stockQuant.productCode ?? '--')),
          DataCell(Text(stockQuant.productName ?? '--')),
          DataCell(Text(stockQuant.productDes ?? '--')),
          DataCell(Text(stockQuant.quantity.toString())),
          DataCell(Text(stockQuant.productUomName ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        // CryButtons.dmsFile(
        //   context,
        //   selectedList.length == 1 ? () => _dmsFile(selectedList[0]) : null,
        // ),
        // !isDisplayDesktop(context)
        //     ? CryButton(
        //         label: "打印标签",
        //         iconData: Icons.view_headline,
        //         onPressed: selectedList.length != 1
        //             ? null
        //             : () => _openTransferLibrary(selectedList[0]))
        //     : Text("")
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          Wrap(
            children: [
              isDisplayDesktop(context) ? form : Container(),
              Padding(
                padding: EdgeInsets.only(top: 24),
                child: isDisplayDesktop(context) ? buttonBar : Container(),
              )
            ],
          ),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    stockQuant = StockQuant();
    // this.locationIdList = [];
    formKey.currentState!.reset();

    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await StockPickingOdooApi.pagePrint(
        data: {"page": page, "domainList": stockQuant.toPrintList()});
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _openTransferLibrary(StockQuant stockQuantList) {
    showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: Print(
          stockQuant: stockQuantList,
        ),
      ),
    ).then((v) {
      if (v != null) {
        _query();
      }
    });
  }

  _search() {
    return showDialog(
      barrierDismissible: false,
      context: context,
      builder: (BuildContext context) => Dialog(
        child: CpkPrintDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockQuant = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockQuant>((e) => StockQuant.fromMapPrint(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.handle) {
          _openTransferLibrary(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.handle,
          enabled: selectedList.length == 1,
          child: ListTile(
            enabled: selectedList.length == 1,
            leading: const Icon(Icons.print),
            title: Text('标签打印'),
          ),
        ),
      ],
    );
  }
}
